#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import os
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('replace_text.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def replace_text_in_file(file_path, old_text, new_text):
    """
    在指定文件中替换文本
    """
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        
        # 检查是否包含要替换的文本
        if old_text not in content:
            return False
        
        # 替换文本
        new_content = content.replace(old_text, new_text)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(new_content)
        
        return True
        
    except Exception as e:
        logger.error(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def main():
    """主函数"""
    # 配置参数
    articles_dir = "Articles"
    old_text = "chucz.org"   #需替换内容
    new_text = "hzccz.asia"     #替换内容
    
    # 检查Articles目录是否存在
    if not os.path.exists(articles_dir):
        logger.error(f"Articles目录不存在: {articles_dir}")
        return
    
    # 统计信息
    total_files = 0
    processed_files = 0
    replaced_files = 0
    
    logger.info(f"开始遍历目录: {articles_dir}")
    logger.info(f"将 '{old_text}' 替换为 '{new_text}'")
    
    # 递归遍历目录
    for root, dirs, files in os.walk(articles_dir):
        for file in files:
            if file.lower().endswith('.md'):
                file_path = os.path.join(root, file)
                total_files += 1
                
                logger.info(f"处理文件: {file_path}")
                
                # 替换文本
                if replace_text_in_file(file_path, old_text, new_text):
                    replaced_files += 1
                    logger.info(f"✓ 成功替换: {file_path}")
                else:
                    logger.info(f"- 无需替换: {file_path}")
                
                processed_files += 1
    
    # 输出统计信息
    logger.info("=" * 50)
    logger.info(f"处理完成!")
    logger.info(f"总文件数: {total_files}")
    logger.info(f"已处理: {processed_files}")
    logger.info(f"已替换: {replaced_files}")
    logger.info(f"无需替换: {total_files - replaced_files}")

if __name__ == "__main__":
    main()
